<template>
  <div class="goods">
    <HeaderNav></HeaderNav> 
    <div class="content">
       <div class="search-bar">
        <input type="text" placeholder="搜索商品" v-model="searchQuery">
        <button class="add-button" @click="openAddModal">添加商品</button>
      </div>
      <div class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th class="name-column">商品编号</th>
              <th class="price-column">商品名称</th>
              <th class="user-column">商品图片</th>
              <th class="user-column">商品分类</th>
              <th class="user-column">价格</th>
              <th class="image-column">商品介绍</th>
              <th class="action-column">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in filteredGoods" :key="item.gid">
              <td class="name-column">{{ item.gid }}</td>
              <td class="price-column">{{ item.gname }}</td>
              <td class="user-column">
                <img :src="`../../public/images/${item.img}`" class="product-image">
              </td>
              <td class="user-column">{{ item.cgid }}</td>
              <td class="user-column">{{ item.price }}</td>
              <td class="image-column">{{ item.introduce }}</td>
              <td class="action-column">
                <button class="delete-button" @click="openEditModal(item)">编辑</button>
                <button class="del-button" @click="confirmDelete(item.gid)">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
     </div>

     <!-- 编辑模态框 -->
    <div v-if="showEditModal" class="modal-overlay">
      <div class="modal-content">
        <h2>编辑商品信息</h2>
        <form @submit.prevent="saveGoods">
          <div class="form-group">
            <label>商品名称</label>
            <input v-model="editingGoods.gname" type="text" required>
          </div>
          <div class="form-group">
      <label>商品图片</label>
      <input type="file" @change="handleImageUpload" accept="image/*">
      <img v-if="imagePreview" :src="imagePreview" class="image-preview">
      <input v-model="editingGoods.img" type="hidden">
    </div>
          <div class="form-group">
            <label>商品分类</label>
            <input v-model="editingGoods.cgid" type="number">
          </div>
           <div class="form-group">
            <label>价格</label>
              <input v-model="editingGoods.price" type="number">
          </div>
          <div class="form-group">
            <label>商品介绍</label>
            <input v-model="editingGoods.introduce" type="text">
          </div>
          <div class="form-actions">
            <button type="button" @click="closeEditModal" class="cancel-button">取消</button>
            <button type="submit" class="save-button">保存</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 添加商品模态框 -->
<div v-if="showAddModal" class="modal-overlay">
  <div class="modal-content">
    <h2>添加新商品</h2>
    <form @submit.prevent="addGoods">
      <div class="form-group">
        <label>商品名称</label>
        <input v-model="newGoods.gname" type="text" required>
      </div>
      <div class="form-group">
        <label>商品图片</label>
        <input type="file" @change="handleImageUpload" accept="image/*">
        <img v-if="imagePreview" :src="imagePreview" class="image-preview">
        <input v-model="newGoods.img" type="hidden">
      </div>
      <div class="form-group">
        <label>商品分类</label>
        <input v-model="newGoods.cgid" type="number">
      </div>
      <div class="form-group">
        <label>价格</label>
        <input v-model="newGoods.price" type="number">
      </div>
      <div class="form-group">
        <label>商品介绍</label>
        <input v-model="newGoods.introduce" type="text">
      </div>
      <div class="form-actions">
        <button type="button" @click="closeAddModal" class="cancel-button">取消</button>
        <button type="submit" class="save-button">保存</button>
      </div>
    </form>
  </div>
</div>
  </div>
</template>

<script setup>
import HeaderNav from '@/views/admin/HeaderNav.vue'
import axios from '../../api/axios';
import { useRoute } from 'vue-router';
import { ref,computed } from 'vue';


const showAddModal = ref(false);
const imagePreview = ref(null);
const selectedFile = ref(null);
const newGoods = ref({
  gname: '',
  img: '',
  cgid: '',
  price: '',
  introduce: '',
});

const goodsinfo = ref([]);
const loading = ref(true);
const searchQuery = ref('');
const showEditModal = ref(false);
const editingGoods = ref({});

// 处理图片上传
const handleImageUpload = (event) => {
  const file = event.target.files[0]; //获取用户选择的第一个文件
  if (file) {
    selectedFile.value = file;
    // 创建预览
    const reader = new FileReader();
    reader.onload = (e) => {
      imagePreview.value = e.target.result;  
    };
    reader.readAsDataURL(file);
    
    // 如果是编辑模式，更新editingGoods.img
    if (showEditModal.value) {
      editingGoods.value.img = file.name;
    } else {
      // 如果是添加模式，更新newGoods.img
      newGoods.value.img = file.name;
    }
  }
};

// 打开添加模态框
const openAddModal = () => {
  newGoods.value = {
    gname: '',
    img: '',
    cgid: '',
    price: '',
    introduce: '',
  };
  imagePreview.value = null;
  selectedFile.value = null;
  showAddModal.value = true;
};

// 关闭添加模态框
const closeAddModal = () => {
  showAddModal.value = false;
  imagePreview.value = null;
  selectedFile.value = null;
};

// 上传图片到服务器
const uploadImage = async () => {
  if (!selectedFile.value) return null;
  
  const formData = new FormData();
  formData.append('image', selectedFile.value);
  
  try {
    const response = await axios.post('/api/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    return response.data.filePath; // 假设后端返回文件路径
  } catch (error) {
    console.error('图片上传失败:', error);
    return null;
  }
};

// 添加商品
const addGoods = async () => {
  try {
    // 先上传图片
    const imagePath = await uploadImage();
    if (imagePath) {
      newGoods.value.img = imagePath;
    }
    
    const payload = {
      gname: newGoods.value.gname,
      img: newGoods.value.img,
      cgid: Number(newGoods.value.cgid),
      price: Number(newGoods.value.price),
      introduce: newGoods.value.introduce
    };

    const response = await axios.post('/api/goods/addGoods', payload);
    if (response.data.code === 200) {
      alert('添加成功');
      fetchGoods();
      closeAddModal();
    } else {
      alert('添加失败: ' + (response.data.msg || '未知错误'));
    }
  } catch (err) {
    console.error("详细错误:", err.response);
    alert('添加失败: ' + (err.response?.data?.message || err.message));
  }
};

// 
//获取商品列表
const fetchGoods = () => {
  axios.post('/api/goods/goodsinfo').then((res) => {
    if (res.data.code === 200) {
      goodsinfo.value = res.data.goods;
    }
  })
  .catch((err) => {
    console.error("请求失败:", err);
  });
};
fetchGoods();

// 搜索过滤
const filteredGoods = computed(() => {
  return goodsinfo.value.filter(goods => 
    goods.gname.toLowerCase().includes(searchQuery.value.toLowerCase()) 
  )
})

// 打开编辑模态框
const openEditModal = (goods) => {
  editingGoods.value = { ...goods };
  showEditModal.value = true;
};

// 关闭编辑模态框
const closeEditModal = () => {
  showEditModal.value = false;
};

// 保存商品信息
const saveGoods = () => {
  // 确保数据类型正确
  const payload = {
    gid: editingGoods.value.gid,
    gname: editingGoods.value.gname,
    img: editingGoods.value.img,
    cgid: Number(editingGoods.value.cgid), // 转换为数字
    price: Number(editingGoods.value.price), // 转换为数字
    introduce: editingGoods.value.introduce,
  };

  console.log("提交的数据:", payload);
  
  axios.post('/api/goods/updateGoods', payload)
    .then(res => {
      if (res.data.code === 200) {
        alert('更新成功');
        fetchGoods();
        closeEditModal();
      } else {
        alert('更新失败: ' + (res.data.msg || '未知错误'));
      }
    })
    .catch(err => {
      console.error("详细错误:", err.response);
      alert('更新失败: ' + (err.response?.data?.message || err.message));
    });
}


// 确认删除
const confirmDelete = (gid) => {
  if(confirm('确定要删除这个商品吗？')) {
    deleteGoods(gid);
  }
};

// 删除商品
const deleteGoods = async (gid) => {
  try {
    const response = await axios.post('/api/goods/delGoods', { gid });
    if (response.data.code === 200) {
      alert('删除成功');
      fetchGoods(); // 刷新商品列表
    } else {
      alert('删除失败: ' + (response.data.msg || '未知错误'));
    }
  } catch (err) {
    console.error("删除失败:", err);
    alert('删除失败，请检查控制台');
  }
};
</script>

<style lang="scss" scoped>
.goods {
  display: flex; /* 启用Flex布局 */
  min-height: 100vh;
  font-family: "PingFang SC", "Helvetica Neue", Arial, sans-serif;
  }
  .content {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
  background-color: #f9f9f9;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

input {
  width: 30%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 10px;
}

.table-container {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 1160px; /* 确保表格在不同屏幕尺寸下都能良好显示 */
}

.data-table th,
.data-table td {
  text-align: left;
  padding: 10px;
  border-bottom: 1px solid #ddd;
}

.data-table th {
  background-color: #f2f2f2;
}

.data-table tr:hover {
  background-color: #f5f5f5;
}

.name-column,.user-column {
  width: 10%;
}
.price-column{
  width: 20%;
}

.quantity-column,
.image-column {
  width: 20%;
}

.action-column {
  width: 10%;
}
.product-image {
  width: 70px;
  height: 70px;
  object-fit: cover;
  border-radius: 4px;
}
.edit-button,
.delete-button {
  padding: 5px 10px;
  margin-right: 5px;
  border: none;
  border-radius: 4px;
  background-color: #007BFF;
  color: #fff;
  cursor: pointer;
}

.edit-button:hover,
.delete-button:hover {
  background-color: #0056b3;
}

// 删除按钮
.del-button {
  padding: 5px 10px;
  border: none;
  border-radius: 4px;
  background-color: #dc3545;
  color: #fff;
  cursor: pointer;
}

.del-button:hover {
  background-color: #c82333;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
}

.modal-content h2 {
  margin-top: 0;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.cancel-button {
  padding: 8px 16px;
  margin-right: 10px;
  background-color: #f0f0f0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.save-button {
  padding: 8px 16px;
  background-color: #007BFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.save-button:hover {
  background-color: #0056b3;
}

//添加商品
.image-preview {
  max-width: 100px;
  max-height: 100px;
  margin-top: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  display: block;
}

.form-group input[type="file"] {
  padding: 5px;
  border: 1px dashed #ccc;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.add-button {
  padding: 10px 15px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}

.add-button:hover {
  background-color: #218838;
}
</style>